<template>
  <div>
    <el-row>
      <el-col :span="8">
        <el-form-item label="sku">
          <el-input maxlength="20" show-word-limit v-model.trim="formInline.productspeccode" placeholder=""  @blur="validateSKU"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item :label="$t('m.page.location')">
          <el-input maxlength="20" show-word-limit v-model.trim="formInline.locationcode" placeholder="" @blur="validateLocation" :disabled="!hasSKU"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item :label="$t('m.inventory.checkqty')">
          <el-input v-input-valid maxlength="20" show-word-limit v-model.number="formInline.checkqty" :disabled="!formInline.locationcode"></el-input>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24" align="right">
        <el-button type="primary" @click="saveCheckqty">{{$t('m.inventory.saveCheckqty')}}</el-button>
      </el-col>
    </el-row>
    <!-- table数据展示 start -->
    <el-row>
      <el-col :span="24">
        <el-table
          empty-text
          fit
          class="table-wrap"
          size="mini"
          :span-method="objectSpanMethod"
          :data="tableData">
          <el-table-column align="center" type="index" :label="$t('m.index')" width="50"></el-table-column>
          <el-table-column align="center" prop="productspeccode" label="SKU" width="150"></el-table-column>
          <el-table-column align="center" prop="locationcode" :label="$t('m.location.locationcode')" width="150"></el-table-column>
          <!-- 暂时封存实际数量，明盘功能才会用到 -->
          <!-- <el-table-column align="center" prop="" label="实际数量"></el-table-column> -->
          <el-table-column align="center" :label="$t('m.state')" width="100">
            <template slot-scope="scope">{{!scope.row.state?$t('m.inventory.state2'):$t('m.inventory.state1')}}</template>
          </el-table-column>
          <el-table-column align="center" prop="checkqty" :label="$t('m.inventory.checkqty')" width="100"></el-table-column>
          <el-table-column align="center" prop="productname" :label="$t('m.in.productname')"></el-table-column>
          <el-table-column align="center" prop="productspec" :label="$t('m.in.productspec')" width="200"></el-table-column>
        </el-table>
      </el-col>
    </el-row>
    <!-- table数据展示 end -->
  </div>
</template>
<script>
export default {
  name:'inventory-sku-detail',
  data(){
    return {
      formInline:{
        locationcode:'', // 库位
        productspeccode:'', // sku
        checkqty:0 // 盘点数量
      },
      tableData:[],
      getMergeRows:[], // 获取table的合并行信息

      hasSKU:false // tableData中是否存在输入的sku
    }
  },
  inject:{
    getInventoryDetail:{
      default:()=>{}
    }
  },
  mounted(){
    this.tableData = this.cloneObject(this.getInventoryDetail().initialStockTakeDetailOutputList)
    // 表格数据排序
    this.tableData.sort((prev,cur)=>{
      if(prev.productid < cur.productid) return 1
      else if(prev.productid > cur.productid) return -1
      else return 0
    })
    this.ruleSpanMethod() // 表格缩进规则
  },
  methods:{
    completeCallback(){
      this.$emit('callback')
    },
    // 表格缩进规则
    ruleSpanMethod(){
      let __index = 0
      let code = ''
      this.getMergeRows = []
      this.tableData.forEach((item,index)=>{
        if(!item.productspeccode){
          this.getMergeRows.push(1)
        } else if(item.productspeccode !== code){
          this.getMergeRows.push(1)
          code = item.productspeccode
          __index = index
        } else {
          if(code){
            ++this.getMergeRows[__index]
            this.getMergeRows.push(0)
          }
        }
      })
    },
    // 表格缩进
    objectSpanMethod({ rowIndex, columnIndex }){
      let MergeArr = [1,5,6]
      if (MergeArr.includes(columnIndex)){
        if(!this.getMergeRows.length){
          return {
            rowspan:1,
            colspan:1
          }
        } else {
          return {
            rowspan:this.getMergeRows[rowIndex],
            colspan:this.getMergeRows[rowIndex] ? 1 : 0
          }
        }
      }
    },
    // tableData中是否存在传入的信息（sku or locationcode）
    getValidateResult(key){
      return this.tableData.some((item)=>{
        return item[key] === this.formInline[key]
      })
    },
    // 验证sku是否存在于当前表格中
    validateSKU(){
      if(!this.formInline.productspeccode) return this.callbackMessage(this.$t('m.skuNotNull'))
      // 这块纯粹是优化用户体验
      if(this.getValidateResult('productspeccode')){
        this.hasSKU=true
      } else {
        this.hasSKU=false
        this.callbackMessage(this.$t('m.inventory.noSKU'))
      }
    },
    // 验证库位编码是否存在于当前表格中
    validateLocation(){
      if(!this.formInline.locationcode) return this.callbackMessage(this.$t('m.inventory.locationnotnull'))
    },
    // 保存单项盘点数据
    saveCheckqty(){
      if(!this.formInline.productspeccode) return this.callbackMessage(this.$t('m.skuNotNull'))
      if(!this.formInline.locationcode) return this.callbackMessage(this.$t('m.inventory.locationnotnull'))
      if(!this.hasSKU) return this.callbackMessage(this.$t('m.inventory.noSKU'))
      if(this.formInline.checkqty==='') return this.callbackMessage(this.$t('m.enter')+this.$t('m.inventory.checkqty'))
      if(isNaN(this.formInline.checkqty)) return this.callbackMessage(this.$t('m.inventory.number'))
      if(this.formInline.checkqty<0) return this.callbackMessage(this.$t('m.inventory.number'))
      // 过滤出当前需要操作的sku list
      let targetSkuList = this.tableData.filter((item)=>{
        return item.productspeccode === this.formInline.productspeccode
      })
      let hasLocationCode = targetSkuList.some((item)=>{
        return item.locationcode === this.formInline.locationcode
      })
      // 如果该库位不存在于当前盘点单中，新增一条记录
      if(!hasLocationCode){
        this.$confirm(this.$t('m.inventory.addInventory'), this.$t('m.noticemessage'), {
          confirmButtonText:this.$t('m.confirm'),
          cancelButtonText:this.$t('m.cancel'),
          type:'warning'
        }).then(() => {
          let {productid,productname,productspec,suppliercode} = this.tableData.find((item)=>{ // 新插入一条记录，sku的明细数据也要提交
            return item.productspeccode === this.formInline.productspeccode
          })
          if(this.formInline.checkqty<=0) return this.callbackMessage(this.$t('m.inventory.number'))
          let options = {
            method:'post',
            url:`/initialstocktake/initialstocktakingforone`,
            data:{
              checkqty:this.formInline.checkqty,
              locationcode:this.formInline.locationcode,
              productspeccode:this.formInline.productspeccode,
              initialstocktakeid:this.getInventoryDetail().initialstocktakeid,
              storage:0,
              state:0,
              productid,
              productname,
              productspec,
              suppliercode,
              entry:1
            }
          }
          let tempTableData = this.cloneObject(this.tableData)
          let length = tempTableData.length
          let index = tempTableData.reverse().findIndex((item)=>{
            return item.productspeccode === this.formInline.productspeccode
          })
          this.$axios(options).then(({ data,message }) => {
            this.tableData.splice(length - index,0,data)
            this.ruleSpanMethod() // 表格缩进规则
            this.saveCheckqtyCallback(message)
          })
        }).catch(() => {
          this.callbackMessage(this.$t('m.inventory.state4'),'info')
        })
      } else {
        let __index = 0
        let {initialstocktakedetailid} = this.tableData.find((item,index)=>{
          if(item.locationcode === this.formInline.locationcode && item.productspeccode === this.formInline.productspeccode) __index = index
          return item.locationcode === this.formInline.locationcode && item.productspeccode === this.formInline.productspeccode
        })
        let options = {
          method:'post',
          url:`/initialstocktake/initialstocktakingforone`,
          data:{
            initialstocktakedetailid,
            checkqty:this.formInline.checkqty,
            entry:1
          }
        }
        this.$axios(options).then(({ data,message }) => {
          let {checkqty} = data || this.formInline
          this.$set(this.tableData[__index],'checkqty',checkqty)
          this.$set(this.tableData[__index],'state',1)

          this.saveCheckqtyCallback(message)
        })
      }
    },
    // 保存后回调（通用方法）
    saveCheckqtyCallback(message){
      // 重置输入环境
      this.hasSKU = false
      this.formInline.locationcode = this.formInline.productspeccode = ''
      this.formInline.checkqty = 0
      // 判断是否已经全部录入
      let isCompleted = this.tableData.every((item)=>{
        return item.state === 1
      })
      // 如果所有盘点单都完成，该单自动进入盘点历史
      isCompleted?this.callbackMessage(this.$t('m.inventory.complete'),'success',2000,this.completeCallback):this.callbackMessage(message,'success')
    }
  }
}
</script>
<style lang="scss" scoped>

</style>